package cn.wenhe9.yygh.user.api;

import cn.wenhe9.yygh.common.helper.JwtHelper;
import cn.wenhe9.yygh.common.result.ResultResponse;
import cn.wenhe9.yygh.model.user.UserInfo;
import cn.wenhe9.yygh.user.service.UserInfoService;
import cn.wenhe9.yygh.user.utils.ConstantWxPropertiesUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/5
 */
@Slf4j
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 生成微信扫描二维码
     * 返回生成二维码需要的参数
     * @return ResultResponse
     */
    @GetMapping("/getLoginParam")
    @ResponseBody
    public ResultResponse genQrConnect(){
        Map<String, Object> map = new HashMap<>();
        map.put("appId", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
        map.put("scope", "snsapi_login");
        String wxOpenRedirectUrl = ConstantWxPropertiesUtils.REDIRECT_URL;
        try {
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            wxOpenRedirectUrl = "";
        }
        map.put("redirectUrl", wxOpenRedirectUrl);
        map.put("state", System.currentTimeMillis() + "");

        return ResultResponse.ok(map);
    }

    /**
     * 回调的方法,得到扫描人信息
     * @param code String
     * @param state String
     * @return String
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/callback")
    public String callback(String code, String state) throws UnsupportedEncodingException {
        //第一步 获取临时的票据 code
        log.info("code:{}", code);
        //第二步 拿着code和微信id和秘钥 请求微信固定地址 得到两个值
        //使用code和appid以及appsecret获取access_token
        // %s 占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(
                baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code
        );
        //使用restTemplate请求这个地址
        String accessTokenInfo = restTemplate.getForObject(accessTokenUrl, String.class);
        //从返回字符串获取两个值 openid 和 access_token
        JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //判断数据库是否存在微信的扫码人的信息
        //根据openid判断

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        if (userInfo == null){
            //第三步 拿着 openid 和 access_token 请求微信地址，得到扫码人的信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";

            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultInfo = restTemplate.getForObject(userInfoUrl, String.class);
            JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);

            //解析用户信息
            //用户昵称
            String nickname = resultUserInfoJson.getString("nickname");
            //用户头像
            String headimgurl = resultUserInfoJson.getString("headimgurl");


            //获取扫码人信息添加数据库
            userInfo = new UserInfo();
            userInfo.setNickName(nickname);
            userInfo.setOpenid(openid);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }

        //返回name和token字符串
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }

        if (StringUtils.isEmpty(name)){
            name = userInfo.getPhone();
        }

        map.put("name", name);
        //判断userINfo是否有手机号 如果手机号为空 返回openid
        //如果手机号不为空 返回openid值是空字符串
        //前端判断 如果openid不为空 绑定手机号 如果openid为空 不需要绑定手机号
        if (StringUtils.isEmpty(userInfo.getPhone())){
            map.put("openid", userInfo.getOpenid());
        }else {
            map.put("openid", "");
        }

        //使用jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL + "/weixin/callback?token=" + token + "&openid=" + map.get("openid") +  "&name=" + URLEncoder.encode(name, "utf-8");
    }
}
